﻿using PLCS.Application.Contracts.LogShowApp.Dtos;
using PLCS.Application.Contracts.OrderApp.Dtos;
using PLCS.Client.IService.LogManager;
using PLCS.Shared.Common.Constant;

using Prism.Services.Dialogs;

using Volo.Abp.ObjectMapping;

namespace PLCS.App.OrderTask.ViewModels.Order;

internal class OrderDetailViewModel : HostDialogViewModel
{
    public OrderDetailViewModel(IObjectMapper<OrderTaskModule> objectMapper, IOrderService orderService, IOperationLogService logShowService)
    {
        _objectMapper = objectMapper;
        _orderService = orderService;
        this._logShowService = logShowService;
        View = "工单管理弹窗";
    }

    private readonly IObjectMapper<OrderTaskModule> _objectMapper;
    private readonly IOrderService _orderService;
    private readonly IOperationLogService _logShowService;
    private OrderDto _model;

    public OrderDto Model
    {
        get { return _model; }
        set { SetProperty(ref _model, value); }
    }

    protected override async void Save()
    {
        try
        {
            SavebuttonIsEnabled = false;
            var order = _objectMapper.Map<OrderDto, OrderEditDto>(Model);
            if (order.Id != Guid.Empty)
            {
                await _orderService.UpdateAsync(order);
                Log("修改", order);
            }
            else
            {
                await _orderService.CreateAsync(order);
                Log("新增", order);
            }

            ShowMessage("操作成功");
            base.Save();
        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }
        finally { SavebuttonIsEnabled = true; }
    }

    public override void OnDialogOpened(IDialogParameters parameters)
    {
        if (parameters.ContainsKey("Value"))
        {
            Model = parameters.GetValue<OrderDto>("Value");
            Title = "编辑";
        }
        else
        {
            Title = "新增";
            Model = new OrderDto();
            Model.UpperNo = Guid.NewGuid().ToString();
            Model.PdLineNo = "未知";
            Model.OrderType = Domain.Shared.Orders.OrderType.工艺工单;
            Model.PlanStartTime = DateTime.Now;
            Model.PlanEndTime = DateTime.Now.AddDays(1);
        }
    }
}